package bid

import (
	"errors"
	"github.com/gomodule/redigo/redis"
	"time"
	"wx-api/adx-bid/cache"
	"wx-api/adx-bid/config"
	"wx-api/adx-bid/model/m_dsp_adv_creative"
	"wx-api/adx-bid/model/m_dsp_adv_plan"
	"wx-api/adx-bid/models/bid/BidModel"
	"wx-api/adx-bid/services/common"
	"wx-api/adx-bid/utils"
)

func DspRtbAdSeach(isdebug bool, req *BidModel.BidRequest, p *m_dsp_adv_plan.DspAdvPlan) (*m_dsp_adv_creative.DspAdvCreative, bool) {
	common.PriMsg(isdebug, "=================================")
	//广告主预算校验
	adv_info, ok := cache.CacheDspAdvertiserMapGet(p.AdvId)
	if !ok || adv_info == nil {
		common.PriMsg(isdebug, "广告主预算校验未通过1")
		return nil, false
	}
	adv_price, ok := DspRtbAdSeachRediaBudget(isdebug, "adv-"+adv_info.Uqid)
	if !ok || adv_price >= adv_info.Budget {
		common.PriMsg(isdebug, "广告主预算校验未通过2")
		return nil, false
	}
	//计划预算校验
	rp_price, ok := DspRtbAdSeachRediaBudget(isdebug, "pl-"+time.Now().Format("2006-01-02")+"-"+p.Uqid)
	if !ok || rp_price >= p.Budget { //预算花完
		common.PriMsg(isdebug, "计划预算校验1")
		return nil, false
	}
	//os := req.GetDevice().GetOs()
	imp := req.GetImp()[0]
	bid_price := float64(imp.GetBidfloor() / 100)
	is_sc := DspRtbAdSeachPlanAdImp(imp)
	common.PriMsg(isdebug, "imp 所需素材：", is_sc)
	//获取计划下所有广告
	ad_arr := cache.GetRunDspAdvPlanResCreativeMap(p.Uqid)
	if len(ad_arr) == 0 {
		common.PriMsg(isdebug, "获取计划下所有广告无")
		return nil, false
	}
	common.PriMsg(isdebug, "创意id：", len(ad_arr), ad_arr)
	max_price := float64(0)
	max_id := []*m_dsp_adv_creative.DspAdvCreative{}
	max_ck := false
	for _, v := range ad_arr {
		tmp, ok := cache.CacheDspAdvCreativeMapGet(v)
		if ok && tmp != nil {
			if tmp.Price == 0 { //广告无出价
				common.PriMsg(isdebug, "广告无出价1")
				continue
			}
			if tmp.Price < bid_price { //低价广告
				common.PriMsg(isdebug, "广告无出价2")
				continue
			}
			imglen := len(tmp.ImgAdm)
			vidlen := len(tmp.VideoAdm)
			if imglen == 0 && vidlen == 0 {
				common.PriMsg(isdebug, "11111")
				continue
			}
			if is_sc == 1 && imglen == 0 {
				common.PriMsg(isdebug, "22222")
				continue
			}
			if is_sc == 2 && vidlen == 0 {
				common.PriMsg(isdebug, "33333")
				continue
			}
			//广告和请求系统匹配
			//if tmp.AppId != "" && os == "ios" && tmp.UnLink == "" {
			//	common.PriMsg(isdebug,"444444")
			//	continue
			//}
			//if tmp.AppId != "" && (os == "android" || os == "harmonyos") && tmp.DpLink == "" {
			//	common.PriMsg(isdebug,"555555")
			//	continue
			//}
			ad_price, oka := DspRtbAdSeachRediaBudget(isdebug, "ad-"+tmp.Uqid)
			if !oka || ad_price >= tmp.Budget { //广告预算查询
				common.PriMsg(isdebug, "6666666")
				continue
			}
			if max_price > 0 && tmp.Price == max_price {
				max_id = append(max_id, tmp)
			}
			if tmp.Price > max_price {
				max_price = tmp.Price
				max_id = nil
				max_id = append(max_id, tmp)
				max_ck = true
			}
		}
	}
	num_max_id := len(max_id)
	common.PriMsg(isdebug, "参与随机的广告数：", num_max_id)
	if !max_ck || num_max_id == 0 {
		common.PriMsg(isdebug, "获取计划下无任何广告")
		return nil, false
	}
	if num_max_id == 1 {
		return max_id[0], true
	}
	tmp_max_id := utils.RandInt64(0, int64(num_max_id))
	return max_id[tmp_max_id], true
}

func DspRtbAdSeachPlanAdImp(imp *BidModel.BidRequest_Imp) int {
	is_sc := 0
	if imp.GetSc() != "" {
		//广告位类型：1信息流，2banner，3开屏，4视频，5横幅，6插屏，7暂停，8贴片，9激励视频
		if imp.GetSc() == "2" || imp.GetSc() == "3" || imp.GetSc() == "5" || imp.GetSc() == "6" {
			is_sc = 1
		} else if imp.GetSc() == "4" || imp.GetSc() == "7" || imp.GetSc() == "8" || imp.GetSc() == "0" {
			is_sc = 2
		}
	} else {
		if imp.GetBanner() != nil {
			is_sc = 1
		}
		if imp.GetVideo() != nil {
			is_sc = 2
		}
	}
	return is_sc
}

func DspRtbAdSeachRediaBudget(isdebug bool, key string) (float64, bool) {
	conn := config.DspAdvBudget.Get()
	if conn == nil {
		common.PriMsg(isdebug, "DspRtbAdSeachPlanAd redis is nil")
		return 0, false
	}
	defer conn.Close()
	b, err := redis.Float64(conn.Do("GET", key))

	if err != nil && !errors.Is(err, redis.ErrNil) {
		common.PriMsg(isdebug, "DspRtbAdSeachPlanAd redis get error:", err)
		return 0, false
	}
	//转化为元
	return (b / 100000), true
}
